package org.ns.framework.datasource.config;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Supplier;

import javax.sql.DataSource;

import org.ns.framework.datasource.redis.RedisConfig;
import org.springframework.boot.context.properties.ConfigurationProperties;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
/**
 * 多数据源选择
 *
 */
@ConfigurationProperties(prefix = "ns.datasource.group")
public class DataSourceConfig {
	
	private Map<String, HikariConfig> hikari = new HashMap<String, HikariConfig>();
	
	private Map<String, DruidDataSourceConfig> druid = new HashMap<String, DruidDataSourceConfig>();

	private Map<String, RedisConfig> redis = new HashMap<String, RedisConfig>();
	
	private Map<String, MongoConfig> mongo = new HashMap<>(); // mongo数据源
	
	private Map<String, Boolean> databaseAutoCommit = new HashMap<String, Boolean>();
	
	
	
	
	public void setHikari(Map<String, HikariConfig> hikari) {
		this.hikari = hikari;
	}

	public Map<String, HikariConfig> getHikari() {
		return hikari;
	}

	public void setDruid(Map<String, DruidDataSourceConfig> druid) {
		this.druid = druid;
	}

	public Map<String, DruidDataSourceConfig> getDruid() {
		return druid;
	}
	
	public Map<String, MongoConfig> getMongo() {
		return mongo;
	}
	
	public void setMongo(Map<String, MongoConfig> mongo) {
		this.mongo = mongo;
	}
	
	public void setDatabaseAutoCommit(Map<String, Boolean> databaseAutoCommit) {
		this.databaseAutoCommit = databaseAutoCommit;
	}

	public Map<String, Boolean> getDatabaseAutoCommit() {
		return databaseAutoCommit;
	}
	
	public boolean autoCommit(String name) {
		if (databaseAutoCommit == null || databaseAutoCommit.size() == 0) {
			return false;
		}
		return databaseAutoCommit.getOrDefault(name, false);
	}
	
	public boolean existName(String name) {
		return this.hikari.containsKey(name) || druid.containsKey(name) || redis.containsKey(name);
	}
	
	public Map<String, Supplier<DataSource>> toDataSources() {
		Map<String, Supplier<DataSource>> map = new HashMap<>();
		for (Entry<String, HikariConfig> entry : hikari.entrySet()) {
			String name = entry.getKey();
			Supplier<DataSource> dataSource = ()->new HikariDataSource(entry.getValue());
			map.put(name, dataSource);
		}
		for (Entry<String, DruidDataSourceConfig> entry : druid.entrySet()) {
			String name = entry.getKey();
			Supplier<DataSource> dataSource = ()-> entry.getValue();
			if (map.put(name, dataSource) != null) {
				throw new RuntimeException(name + ": 当前数据源的配置重复,请检查命名");
			}
		}
		return map;
	}

	public Map<String, RedisConfig> getRedis() {
		return redis;
	}
}
